package com.kingdee.fpy;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.awt.image.BufferedImage;
import java.io.IOException;

public class PdfQRCodeUtil {
    static MultiFormatReader formatReader = new MultiFormatReader();
    // 90像素的二维码图片宽度既可保证性能，又可保证解析准确
    static final int QR_WIDTH = 90;

    public static String getNewInvoiceNo(byte[] fileBytes) throws IOException, NotFoundException {
        BufferedImage img = null;

        // 使用自优化过的加载方式
        PDDocument document = PDDocumentFpy.load(fileBytes);
        // 默认第一页是电子发票
        PDResources resources = document.getPage(0).getResources();
        for (COSName name : resources.getXObjectNames()) {
            if (resources.isImageXObject(name)) {
                PDImageXObject obj = (PDImageXObject) resources.getXObject(name);
                img = obj.getImage(null, obj.getWidth() <= QR_WIDTH ? 1 : obj.getWidth() / 90);
                break;
            }
        }

        document.close();

        if (img == null)
            return null;

        String info = getInvoiceQR(img);
        if (StringUtils.isEmpty(info))
            return null;

        // 全电发票二维码第4位是发票号码，长度为20
        String[] codes = info.split(",");
        if (codes.length < 4)
            return null;

        return codes[3];
    }

    protected static String getInvoiceQR(BufferedImage img) throws NotFoundException {
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(img)));
        Result result = formatReader.decode(binaryBitmap);
        if (result != null) {
            return result.getText();
        }
        return null;
    }
}
